//
//  LYPublicVideoViewController.m
//  artist
//
//  Created by laotang on 16/4/17.
//  Copyright © 2016年 viviyoo. All rights reserved.
//

#import "LYPublicVideoViewController.h"
#import <Photos/Photos.h>
#import <Photos/PHAsset.h>
#import <AssetsLibrary/AssetsLibrary.h>  // 必须导入
#import <QiniuSDK.h>
#import <SVProgressHUD.h>
#import "NSDate+Utils.h"
#import <Masonry.h>
#import <AVKit/AVPlayerViewController.h>
//#import "MPMoviePlayerController.h"
#import <MediaPlayer/MediaPlayer.h>
// 照片原图路径
#define KOriginalPhotoImagePath   \
[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"OriginalPhotoImages"]

// 视频URL路径
#define KVideoUrlPath   \
[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"VideoURL"]

// caches路径
#define KCachesPath   \
[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]

@interface LYPublicVideoViewController()
@property (nonatomic, strong) NSMutableArray *videoArray;
@property (nonatomic, strong) AVPlayer *player;

@property (nonatomic, strong) ALAsset *assetItem;

@property (nonatomic, strong) NSArray *assetArray;
@property (nonatomic, strong) NSString *videoDate;
@property (nonatomic, strong) NSString *fileName;
@property (nonatomic, strong) NSURL *videoURL;
@property (nonatomic, assign) CGSize assetItemSize;
@property (nonatomic, assign) AVPlayerLayer * playerLayer;
@property (nonatomic, strong) QNUploadManager *uploadManager;
@property (nonatomic, strong) UITextField *textField;

@property (nonatomic, strong) NSString *videoLink;
@property (nonatomic, strong) NSString *imageLink;
@property (nonatomic, strong) UIImage *videoImage;
@property (nonatomic, strong) MPMoviePlayerController *playerController;


@end


@implementation LYPublicVideoViewController
- (void)viewDidLoad{
    [super viewDidLoad];
    self.videoArray = [NSMutableArray array];
    self.filterType = QBImagePickerControllerFilterTypeVideos;
    [self.addPhotoView.addButton setImage:[UIImage imageNamed:@"添加视频"] forState:UIControlStateNormal];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endPlay) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    
    
    [self.editContentView setMy_Y: 44];
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 0, LYScreenWidth  -20, 44)];
    [self.view addSubview:self.textField];
    self.textField.placeholder = @"课程名称";
    self.textField.textAlignment = NSTextAlignmentLeft;
    self.textField.borderStyle= UITextBorderStyleNone;
    
    UIView *lineView= [[UIView alloc] initWithFrame:CGRectMake(0, 44, LYScreenWidth, 0.5)];
    lineView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.4];
    [self.view addSubview:lineView];
    WS(weakSelf)
    [self.editContentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(weakSelf.view);
        make.top.mas_equalTo( 44);
        make.height.mas_equalTo(170);
    }];
    
    self.placeHoldLabel.text = @"课程介绍";
    
    //
    //
    //    MPMoviePlayerViewController * movicVC =  [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:@""]];
    
    
    
}

- (void)endPlay{
    
    [self.playerController.view removeFromSuperview];
    self.playerController = nil;
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
}
#pragma mark - override


- (void)playButtonDidPress:(UIButton *)button{
    
    WS(weakSelf)
    
    
    
    [self.playerController play];
    
    //    [self saveVideoWithUrl:self.videoURL withFileName:self.fileName WirteSuccess:^{
    //
    //        NSURL *url = [NSURL URLWithString:[weakSelf pathForFileName:weakSelf.fileName]];
    ////        MPMoviePlayerViewController *vc = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
    ////                      [ self.navigationController pushViewController:vc animated:YES];
    //
    //        MPMoviePlayerController* player = [[MPMoviePlayerController alloc] init];
    //
    //        [player view].backgroundColor = [UIColor clearColor];
    //        player.scalingMode = MPMovieScalingModeNone;
    //        player.controlStyle = MPMovieControlStyleDefault;
    //        player.backgroundView.backgroundColor = [UIColor clearColor];
    //        player.repeatMode = MPMovieRepeatModeNone;
    //
    //        NSLog(@"%@",weakSelf.videoURL);
    //        [player setContentURL:url];
    //        [weakSelf.view addSubview:player.view];
    //        [player setFullscreen:YES animated:YES];
    //        [player prepareToPlay];
    //        [player play];
    //    }];
    //
    //
    //    MPMoviePlayerController* player = [[MPMoviePlayerController alloc] init];
    //
    //    [player view].backgroundColor = [UIColor clearColor];
    //    player.scalingMode = MPMovieScalingModeNone;
    //    player.controlStyle = MPMovieControlStyleDefault;
    //    player.backgroundView.backgroundColor = [UIColor clearColor];
    //    player.repeatMode = MPMovieRepeatModeNone;
    //    player.movieSourceType = MPMovieSourceTypeFile ;
    //
    //    NSString *urlString = self.videoURL.absoluteString;
    //    NSLog(@"===============%@",urlString);
    //    NSURL *url = [NSURL URLWithString:urlString];
    //    [player setContentURL:url];
    //    [weakSelf.view addSubview:player.view];
    //    [player setFullscreen:YES animated:YES];
    //    [player prepareToPlay];
    //    [player play];
    //    [MPMoviePlayerViewController ]
    
    
    
    
    //   MPMoviePlayerViewController * movieVC =  [[MPMoviePlayerViewController alloc] init];
    //    [movieVC.moviePlayer setContentURL:self.videoURL];
    //    [movieVC.moviePlayer prepareToPlay];
    ////    [self.view addSubview:moviePlayerController.view];//设置写在添加之后   // 这里是addSubView
    ////    [moviePlayerController.view setFrame:self.view.frame];
    //    movieVC.moviePlayer.shouldAutoplay=YES;
    //    movieVC.moviePlayer.movieSourceType=MPMovieSourceTypeFile;
    //    movieVC.moviePlayer.fullscreen = YES;
    //    [movieVC.moviePlayer setControlStyle:MPMovieControlStyleDefault];
    //    [movieVC.moviePlayer play];
    //    [self presentMoviePlayerViewControllerAnimated:movieVC];
    //    [movieVC dismissViewControllerAnimated:YES completion:^{yy
    //
    //    }];
    
    //    if(self.playButtton.selected){
    //        [self.player play];
    //    }else{
    //        [self.player pause];
    //
    //    }
    
    
}


- (void)addPhotoButtonPressed{
    
    QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
    imagePickerController.filterType = self.filterType;
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.maximumNumberOfSelection = 1;
    [self presentViewController:imagePickerController animated:YES completion:NULL];
}

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets
{
    
    
    //    self.addPhotoView.hidden = YES;
    [self dismissViewControllerAnimated:YES completion:nil];
    ALAsset *assetItem = [assets firstObject];
    self.assetItem = assetItem;
    self.videoURL = [[assetItem defaultRepresentation] url];
    NSString *name = [[NSDate date] string];
    self.fileName = [NSString stringWithFormat:@"%@%@.mp4",name,[[assetItem defaultRepresentation] filename]];
    
    self.assetItemSize = [[assetItem defaultRepresentation] dimensions];
    
    self.videoImage = [UIImage imageWithCGImage:[[assetItem defaultRepresentation] fullResolutionImage]];
    NSURL *url = [[assetItem defaultRepresentation] url];
    
    NSLog(@"%@", url);
    
    
    
    //    AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:self.videoURL options:nil];
    //    self.videoDate= [assetItem valueForProperty:ALAssetTypeVideo];
    //    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:assetItem];
    //    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    //    self.player = [AVPlayer playerWithURL:self.videoURL];
    //    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    //    [self.playerLayer addSublayer:self.playButtton.layer];
    //    [self.view.layer addSublayer:self.playerLayer];
    
    
    CGFloat height = 0.0;
    if (self.assetItemSize.width > self.assetItemSize.height){
         height = LYScreenWidth / self.assetItemSize.width  *self.assetItemSize.height;

    }else{
         height = LYScreenWidth / self.assetItemSize.height * self.assetItemSize.width;

    }
    CGRect rect  = CGRectMake(0, self.addPhotoView.My_Y, LYScreenWidth,  height);

    
    if(height > LYScreenHeight - self.addPhotoView.My_Y - 10){
        
        height = LYScreenHeight - self.addPhotoView.My_Y - 20;
    }
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:rect];
    imageView.image = self.videoImage;
    imageView.userInteractionEnabled = YES;
    [self.view addSubview:imageView];
    MPMoviePlayerController *moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:self.videoURL];
    //
    self.playerController = moviePlayerController;
    
    [moviePlayerController.view setFrame:rect];
    moviePlayerController.shouldAutoplay=YES;
    
    moviePlayerController.movieSourceType=MPMovieSourceTypeUnknown;
    moviePlayerController.fullscreen = NO;
    [moviePlayerController setControlStyle:MPMovieControlStyleDefault];
    [moviePlayerController setScalingMode:MPMovieScalingModeNone];
    
    //    [moviePlayerController setmask]
    [moviePlayerController prepareToPlay];
    [self.view addSubview:moviePlayerController.view];//设置写在添加之后   // 这里是addSubView
    
    
    [self.choseBigImageLists addObject:self.videoImage];
    self.addPhotoView.imageUrlArray = self.choseBigImageLists;
    [self.addPhotoView resetPhotoView];
    
    
}


- (void)prepareToreplay{
    
    [_player seekToTime:CMTimeMake(0, 1)];
    [_player pause];
    
    
}

#pragma mark - override

- (void)publicData{
    
    if (!self.textField.text.length){
        [SVProgressHUD showErrorWithStatus:@"请输入视频标题"];
    }
    
    if(!self.textView.text.length){
        [SVProgressHUD showErrorWithStatus:@"请输入内容"];
        return;
    }
    
    
    if(!self.assetItem){
        [SVProgressHUD showErrorWithStatus:@"请选择视频"];
        return;
    }
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    
    WS(weakSelf)
    
    [SVProgressHUD showWithStatus:@"正在准备上传"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [self saveVideoWithUrl:self.videoURL withFileName:self.fileName WirteSuccess:^{
        [SVProgressHUD showWithStatus:@"正在上传"];
        
        
        NSLog(@"fileName: %@",[self pathForFileName:self.fileName]);
        NSData *data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:[self pathForFileName:self.fileName]]];
        QNUploadOption * option = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
            [SVProgressHUD showProgress:percent status:@"正在上传视频"];
        }];
        [upManager putData:data key:nil token:weakSelf.qiNiuToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            
            
            [[NSFileManager defaultManager] removeItemAtPath:KVideoUrlPath error:nil];
            weakSelf.videoLink = [NSString stringWithFormat:@"http://7xrlrd.com1.z0.glb.clouddn.com/%@",resp[@"key"]];
            
            NSData *imageData = UIImageJPEGRepresentation(self.videoImage, 0.3);
            QNUploadOption * Imageoption = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
                NSLog(@"%f", percent);
            }];
            [upManager putData:imageData key:nil token:weakSelf.qiNiuToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                weakSelf.imageLink = [NSString stringWithFormat:@"http://7xrlrd.com1.z0.glb.clouddn.com/%@",resp[@"key"]];
                
                [weakSelf postToServer];
            } option:Imageoption];
            
            
        } option:option];
    }];
    
    //    NSString *name = [[NSDate date] string];
    //    NSString *videoName = [NSString stringWithFormat:@"%@.mp4",name];
    //
    
    //    self.uploadManager = upManager;
    //    [upManager putData:data key:nil token:self.qiNiuToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
    //        [SVProgressHUD dismiss];
    //
    //        [[NSFileManager defaultManager] removeItemAtURL:[NSURL URLWithString:KVideoUrlPath] error:nil];
    //         // 上传图片
    
    //
    //        NSData *imageData  = UIImageJPEGRepresentation(self.videoImage, 0.75);
    //        QNUploadOption *imageOption = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
    //        }];
    //        [upManager putData:imageData key:nil token:self.qiNiuToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
    //            NSLog(@"上传图片成功");
    //              self.imageLink = [NSString stringWithFormat:@"http://7xrlrd.com1.z0.glb.clouddn.com/%@",key];
    //            [self postToServer];
    //
    //        } option:imageOption];
    //
    //
    //    } option:option];
    //
    
    
}

- (NSString *)pathForFileName:(NSString *)fileName{
    
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:KVideoUrlPath]) {
        [fileManager createDirectoryAtPath:KVideoUrlPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    
    
    return [KVideoUrlPath stringByAppendingPathComponent:fileName];
    
}


- (void)postToServer{
    
    NSLog(@"%@", [AppDelegate shareInstance].token );
    WS(weakSelf)
    [LYRequestTool postVideoWithToken:[AppDelegate shareInstance].token title:self.textField.text desc:self.textView.text link:self.videoLink image:self.imageLink  success:^{
        [SVProgressHUD showSuccessWithStatus:@"发布成功"];
        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
    } failure:^(NSString *code, NSString *message) {
        [SVProgressHUD showErrorWithStatus:message];
    }];
}


//
//// 将原始视频的URL转化为NSData数据,写入沙盒
//- (void)saveVideoWithUrl:(NSURL *)url withFileName:(NSString *)fileName WirteSuccess:(void(^)())success
//{
//
//    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        if (url) {
//            [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {
//                ALAssetRepresentation *rep = [asset defaultRepresentation];
//                NSString * videoPath = [self pathForFileName:fileName];
//                char const *cvideoPath = [videoPath UTF8String];
//                FILE *file = fopen(cvideoPath, "a+");
//                if (file) {
//                    const int bufferSize = 11024 * 1024;
//                    // 初始化一个1M的buffer
//                    Byte *buffer = (Byte*)malloc(bufferSize);
//                    NSUInteger read = 0, offset = 0, written = 0;
//                    NSError* err = nil;
//                    if (rep.size != 0)
//                    {
//                        do {
//                            read = [rep getBytes:buffer fromOffset:offset length:bufferSize error:&err];
//                            written = fwrite(buffer, sizeof(char), read, file);
//                            offset += read;
//                        } while (read != 0 && !err);//没到结尾，没出错，ok继续
//                    }
//
//                    if(success){
//                        success();
//                    }
//
//                    free(buffer);
//                    buffer = NULL;
//                    fclose(file);
//                    file = NULL;
//                }
//            } failureBlock:nil];
//        }
//    });
//}

- (void)saveVideoWithUrl:(NSURL *)url withFileName:(NSString *)fileName WirteSuccess:(void(^)())success
{
    AVURLAsset * urlAsset = [[AVURLAsset alloc] initWithURL:self.videoURL options:nil];
    AVAssetExportSession * exportSession = [AVAssetExportSession exportSessionWithAsset:urlAsset presetName:AVAssetExportPresetLowQuality];
    exportSession.outputFileType = AVFileTypeMPEG4;
    exportSession.outputURL = [NSURL fileURLWithPath:[self pathForFileName:self.fileName]];//输出的上传路径，文件不能已存在
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:self.videoURL options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    NSLog(@"%@",compatiblePresets);
    if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetLowQuality];
        NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复，在测试的时候其实可以判断文件是否存在若存在，则删除，重新生成文件即可
        [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
        NSString * resultPath = [self pathForFileName:self.fileName];
        NSLog(@"resultPath = %@",resultPath);
        exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
        exportSession.outputFileType = AVFileTypeMPEG4;
        exportSession.shouldOptimizeForNetworkUse = YES;
        [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
         
         {
             
             switch (exportSession.status) {
                     
                 case AVAssetExportSessionStatusUnknown:
                     
                     NSLog(@"AVAssetExportSessionStatusUnknown");
                     
                     break;
                     
                 case AVAssetExportSessionStatusWaiting:
                     
                     NSLog(@"AVAssetExportSessionStatusWaiting");
                     
                     break;
                     
                 case AVAssetExportSessionStatusExporting:
                     
                     NSLog(@"AVAssetExportSessionStatusExporting");
                     
                     break;
                     
                 case AVAssetExportSessionStatusCompleted:{
                     if (success){
                         success();
                     }
                 }
                     break;
                     
                 case AVAssetExportSessionStatusFailed:
                     
                     break;
                     
             }
             
         }];
    }
    
    
}

@end
